import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store=new Vuex.Store({
    state:{
       shopcartList:[]
    },
    mutations:{
        SET_SHOPCARTLIST(state,payload){
            state.shopcartList=payload
        }
    },
    actions:{
        async getShopcartListAsync(context){
            console.log('-----actions下的getShopcartListAsync---------');
            //像后端接口发送请求来得到数据
            const result=await Vue.prototype.$api.shopcart.getShopcartData()
            context.commit('SET_SHOPCARTLIST',result.data)
        },
        async changeNumAsync(context,payload){
            console.log('-----actions下的changeNumAsync---------');
            console.log('payload',payload);
            const result=await Vue.prototype.$api.shopcart.changeNum(payload)
            console.log('result',result);
            if(result.code){
                context.dispatch("getShopcartListAsync")
            }
        },
        async changeNumByInputAsync(context,payload){
            console.log('-----actions下的changeNumByInputAsync---------');
            console.log('payload',payload);
            const {code}=await Vue.prototype.$api.shopcart.changeNumByInput(payload)
            if(code){
                context.dispatch("getShopcartListAsync")
            }
        },
        async changeCheckedStatus(context,payload){
            console.log('-----actions下的changeCheckedStatus---------');
            console.log('payload',payload);
            const {code}=await Vue.prototype.$api.shopcart.checkProducts(payload)
            if(code){
                context.dispatch("getShopcartListAsync")
            }
        }
    },
    getters:{
        total(state){
            return state.shopcartList.filter(item=>item.checked).reduce((prev,cur)=>prev+cur.price*cur.num,0)
        }
    }
})
export default store